package com.moguo.managementsystembackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moguo.managementsystembackend.mapper.UserMapper;
import com.moguo.managementsystembackend.model.User;
import com.moguo.managementsystembackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.moguo.managementsystembackend.contant.UserConstant.USER_LOGIN_STATE;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    /*
    盐值，混淆密码
     */
    private  static final String SALT="moguo";


    @Override
    public long userRegister(String userAccount, String userPassword, String checkpassword) {
       // 1、用户在前端输入账户和密码以及校验码
       if(StringUtils.isAllBlank(userAccount,userPassword,checkpassword)){
           return -1;
       }
       // 2、账号不小于4位
        if(userAccount.length()>4){
            return -1;
        }
        //3、密码不小于4位
        if (userPassword.length()>4){
            return -1;
        }

        // 4、账号不包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
       // 5、密码和校验密码相同
       if(userPassword.equals(checkpassword)){
           return -1;
       }

        //6、账号不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count>0){
            return -1;
        }

        //7、 密码加密
        final String SALT="moguo";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //8、插入数据
        User   user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if(saveResult){
            return -1;
        }
        return user.getId();
    }


/**
* @Description:
* @Param: [userAccount, userPassword, request]
* @return: com.moguo.managementsystembackend.model.User
* @Author: moguo
* @Date: 2024/5/4
*/
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1、用户在前端输入账户和密码以及校验码
        if(StringUtils.isAllBlank(userAccount,userPassword)){
            return null;
        }
        // 2、账号不小于4位
        if(userAccount.length()>4){
            return null;
        }
        //3、密码不小于4位
        if (userPassword.length()>4){
            return null;
        }

        // 4、账号不包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        //5、 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());

        //6、查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //7、用户不存在
        if(user == null){
            log.info("user login failed,userAccount cannot match userPassword");
            return null;
        }
        //8、用户脱敏
       User safetyUser=getSafetyUser(user);
       //9、记录用户的登录态
         request.getSession().setAttribute(USER_LOGIN_STATE,user);
        return safetyUser;
    }
    /**
    * @Description: 用户脱敏
    * @Param: [originUser]
    * @return: com.moguo.managementsystembackend.model.User
    * @Author: moguo
    * @Date: 2024/5/4
    */
    @Override
    public User getSafetyUser(User originUser){
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        return safetyUser;
    }


}